package com.tsd.common.controller;

import cn.hutool.db.Entity;
import com.tsd.common.entity.CommonShortUrlExt;
import com.tsd.common.service.CommonShortUrlService;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.utils.ExceptionUtil;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.datasource.DataSourceInitService;
import com.tsd.system.entity.SysAccountSetExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import java.util.Map;


/**
 * 短链接跳转
 *
 * @author
 */
@Controller
@Scope("prototype")
public class ShortController extends BaseController {

    public static final Logger LOGGER = LoggerFactory.getLogger(ShortController.class);

    @Resource
    private CommonShortUrlService commonShortUrlService;
    @Resource
    private Environment environment;

    @GetMapping("/s/{id}/{code}")
    public ModelAndView index(@PathVariable("id") Long id, @PathVariable("code") String code) {
        RedirectView redirectView = new RedirectView();
        try {
            Map<String, Object> map = super.getParams(request);
            Entity entity = DataSourceInitService.getAccountSet(id);
            DataSourceContextHolder.setDataSourceType(entity == null ? DataSourceContextHolder.DEFAULT_ACCOUNT_SET_SID : entity.getStr("code"));
            CommonShortUrlExt urlExt = commonShortUrlService.queryValidByCode(code);
            if (urlExt != null) {
                String longUrl = urlExt.getLong_url();
                if (!map.isEmpty()) {
                    //map存放动态参数,动态参数每次重新生成
                    if (CommonShortUrlExt.BIZ_TYPE_DTS_GOODS.equals(urlExt.getBiz_type())) {
                        String openlink = commonShortUrlService.genDirectWxMiniUrl(map, 1, urlExt);
                        if (!HlpUtils.isEmpty(openlink)) {
                            longUrl = openlink;
                        }
                    }
                }
                redirectView.setUrl(longUrl);
                if (urlExt.isNeed_upate()) {
                    commonShortUrlService.saveCommonShortUrl(urlExt, null);
                }
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        }
        if (HlpUtils.isEmpty(redirectView.getUrl())) {
            String contextPath = environment.getProperty("server.servlet.context-path");
            redirectView.setUrl(contextPath + "/auth/404");
        }
        // 301永久重定向，避免网络劫持
        redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        return new ModelAndView(redirectView);
    }
}
